function writestcfiles(fourd, filetmp, sdim)
% writestcfiles  - create STC files from a 4D array
%
% FORMAT:       writestcfiles(fourd, filetmp [, sdim])
%
% Input fields:
%
%       fourd       4-D data array (if not within 0..32767, will be norm.)
%       filetmp     filename template with one %d sequence
%       sdim        dimension of slices (default: 1)

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% check arguments
if nargin < 2 || ...
   ~isnumeric(fourd) || ...
   ~any([3, 4] == ndims(fourd)) || ...
   ~ischar(filetmp) || ...
    isempty(strfind(filetmp(:)', '%d'))
    error( ...
        'BVQXtools:BadArguments', ...
        'Invalid or missing argument given.' ...
    );
end
filetmp = filetmp(:)';
if nargin < 3 || ...
   ~isa(sdim, 'double') || ...
    numel(sdim) ~= 1 || ...
    isinf(sdim) || ...
    isnan(sdim) || ...
    sdim < 1 || ...
    sdim > 4
    sdim = 1;
else
    sdim = real(sdim);
end
if sdim ~= 1
    fourd = permute(fourd, [sdim, setdiff(1:ndims(fourd), sdim)]);
end

% get dimensions
ad = size(fourd);

% check datatype
mna = min(fourd(:));
if mna < 0
    fourd = fourd - mna;
end
mxa = max(fourd(:));
if mxa >= 32767.5
    fourd = fourd / (mxa / 32768);
end
fourd = round(fourd);

% get a slice
slice = BVQXfile('new:stc');
slice.NrOfRows = ad(2);
slice.NrOfCols = ad(3);
slice.NrOfVolumes = ad(4);

% iterate over slices
for sc = 1:ad(1)
    slice.STCData = squeeze(fourd(sc, :, :, :));
    slice.SaveAs(sprintf(filetmp, sc));
end

% clear object
slice.ClearObject;
